;
(function() {
    new Vue({
        el: '#createCm',
        data: {
			//流失原因列表
			lsListData: [],
			lsSelectData: [],
			
            type: [{ name: '公司', type: 'QY' }, { name: '个人', type: 'PE' }],
            typeAct: 'QY',
            blacklist: [{ name: '是', type: 'Y' }, { name: '否', type: 'N' }],
            blacklistAct: 'N',
            industryData: [],
            selectedIndustry: [],
            customerStateData: [
                
            ],
            selectedCustomerState: [],
            channelTypeData: [],
            selectedChannelType: [],
            channelNameData: [],
            allchannelNameData: [],
            selectedChannelName: [],
            selectedChannelNameVal: [],
            processData: [],
            selectedProcess: [],
            fieldData: [],
            //input v-model
            cmName: '',
            jcName: '',
            idcode: '',
            email: '',
            lperson: '',
            phone: '',
            zipcode: '',
            address: '',
            memo: '',
            biz_info: {
                "biz_register_code": "",
                "operate_status": "",
                "social_unified_credit_code": "",
                "register_agency": "",
                "biz_organization_code": "",
                "biz_company_type": "",
                "biz_legal_person_name": "",
                "operation_scope": "",
                "register_capital": "",
                "establish_time": "",
                "register_addr": "",
                "operation_end_time": ""
            },
            //红色框框警告
            cmflag: false,
            cmstatusflag: false,
            industryflag: false,
            lspeopleflag: false,
            lsphoneflag: false,
            qdflag: false,
            qdnmflag: false,
            validataflag: false,
            //模糊搜索输入的内容
            cmName: '',
            //模糊搜索结果
            cmNameList: '',
            // 是否显示模糊搜索结果
            showcmNameList: '',
            //选择公司的名称
            company_name: '',
            //工商信息
            IndustryDetail: {
                bizRegisterCode: '',
                operateStatus: '',
                socialUnifiedCreditCode: '',
                registerAgency: '',
                bizOrganizationCode: '',
                bizCompanyType: '',
                bizLegalPersonName: '',
                establishTime: '',
                registerCapital: '',
                operationEndTime: '',
                registerAddr: '',
                operationScope: '',
            },
            //预留工商编号
            reserceCode: '',
						//
						tmpData: [],
						resData: []
        },
        computed: {
            infodetail() {
                return {
                    "biz_register_code": this.IndustryDetail.bizOrganizationCode || '#',
                    "operate_status": this.IndustryDetail.operateStatus || '',
                    "social_unified_credit_code": this.IndustryDetail.socialUnifiedCreditCode || '#',
                    "register_agency": this.IndustryDetail.registerAgency || '#',
                    "biz_organization_code": this.IndustryDetail.bizOrganizationCode || '#',
                    "biz_company_type": this.IndustryDetail.bizCompanyType || '#',
                    "biz_legal_person_name": this.IndustryDetail.bizLegalPersonName || '#',
                    "operation_scope": this.IndustryDetail.operationScope || '#',
                    "register_capital": this.IndustryDetail.registerCapital || '#',
                    "establish_time": this.IndustryDetail.establishTime || '#',
                    "register_addr": this.IndustryDetail.registerAddr || '#',
                    "operation_end_time": this.IndustryDetail.operationEndTime || '#'
                }
            }
        },
        methods: {
			
			getLsReason() {
			  var that = this
			  hlhttp.get({
			    url: 'configure/dict',
			    data: {
			      module_code: 'ZHSH',
			      config_name: 'ZS_LOSS_REASON'
			    },
			    success: function (data) {		
					var temp = data.filter((item) => {return item.status == 'Y'})
					
			      that.lsListData = hlArrayUtil.replaceData(temp, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
			    },
			  })
			},

            inputChange() {
                var that = this
                setTimeout(function() {
                    that.showcmNameList = false
                }, 1000)
            },
            // 获取搜索结果
            //本地
            getcmNameList() {
                if (this.cmName) {
                    hlhttp.get({
                        url: 'customer/search_from_qxb',
                        data: {
                            customer_name: this.cmName,
                            local_flag: 'Y'
                        },
                        success: (res) => {
                            this.cmNameList = res
                            if (res) {
                                this.showcmNameList = true
                            }
                        }
                    })
                }
            },
            //第三方
            show: function() {
                if (this.cmName) {
                    hlhttp.get({
                        url: 'customer/search_from_qxb',
                        data: {
                            customer_name: this.cmName,
                            local_flag: 'N'
                        },
                        success: (res) => {
                            this.cmNameList = res
                            if (res) {
                                this.showcmNameList = true
                            }
                        }
                    })
                }
            },
            //选择公司
            selectcmName(name) {
                this.cmName = name
                this.company_name = name
                this.getcompanyDetail()
            },
            //获取工商信息
            getcompanyDetail() {
                if (this.company_name) {
                    hlhttp.get({
                        url: 'customer/industry_and_commerce_info',
                        data: { company_name: this.company_name },
                        success: (res) => {
                            this.showcmNameList = false
                            this.IndustryDetail = res
                            if (!this.idcode) {
                                this.idcode = this.IndustryDetail.socialUnifiedCreditCode;
                                this.reserceCode = this.IndustryDetail.socialUnifiedCreditCode;
                            }
                        }
                    })
                }
            },
            //关闭弹窗
            hidePopValidata() {
                this.validataflag = false
            },
            // 检测自定义字段填写是否符合要求
            checkCustom() {
                let flag = true
                this.resData.map(item => {
                	if (item.requiredFlag == 'Y' && (!item.value || !item.value.length) && item.type != 'line') {
                	  flag = false
                	}
                })	
                return flag
            },
            selectedCustomerStateChange(){
                if(this.selectedCustomerState[0]!=='LS'){
                  this.lsSelectData.splice(0,1)
                }
              },
            //验证客户
            validataCustomer() {
                if (!this.checkCustom()) {
                    hl.toast('请完成自定义字段')
                    return
                }
                this.cmflag = false;
                this.cmstatusflag = false;
                this.industryflag = false;
                this.lspeopleflag = false;
                this.lsphoneflag = false;
                this.qdflag = false;
                this.qdnmflag = false;

                if (!this.cmName) {
                    this.cmflag = true;
                    hl.toast('请填写客户名称')
                    return
                }
                if (!this.selectedCustomerState.length) {
                    hl.toast('请选择客户状态')
                    return
                }
                if (this.selectedCustomerState[0]=='LS' && !this.lsSelectData.length) {
                    hl.toast('请选择流失原因')
                    return
                }
                if (!this.lperson) {
                    hl.toast('请填写联系人')
                    return
                }
                if (!this.phone) {
                    hl.toast('请填写联系电话')
                    return
                }
                
                if (!this.selectedChannelType.length) {
                    // this.qdflag = true;
                    hl.toast('请选择渠道分类')
                    return
                }

                hlhttp.get({
                    url: 'customer/check_customer_repeat',
                    data: { customer_id: '#', customer_name: this.cmName, cstmr_contact: this.lperson, cstmr_contact_no: this.phone, customer_type: this.typeAct },
                    success: (res) => {
                        if (res.repeat == 'N') { this.postCm() }
                        if (res.repeat == 'Y') { this.validataflag = true }
                    }
                })
            },
            getIndustryData() {
                var self = this
                hlhttp.get({
                    url: 'configure/industry/dict',
                    success: data => {
                        self.industryData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
                    }
                })
            },
            getChannelTypeData() {
                var self = this
                hlhttp.get({
                    url: 'configure/dict',
                    data: { module_code: 'ZHSH', config_name: 'ZS_CHANNEL_CATE' },
                    success: data => {
                        let arr = []
                        data.map(item =>{
                          if(item.status == 'Y'){
                            arr.push(item)
                          }
                        })
                        self.channelTypeData = hlArrayUtil.replaceData(arr, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])

                        if (window.sessionStorage.getItem('RENT_BUSINESS_CUSTOMER')) {
                            var data = JSON.parse(window.sessionStorage.getItem('RENT_BUSINESS_CUSTOMER'));

                            if (data.industryCode) self.selectedIndustry.push(data.industryCode)
                            if (data.channelCategoryCode) self.selectedChannelType.push(data.channelCategoryCode)
                            if (data.channelNameCode) self.selectedChannelName.push(data.channelNameCode)
                            if (data.channelNameValue) self.selectedChannelNameVal.push(data.channelNameValue)

                            self.typeAct = data.customerType;
                            self.cmName = data.customerName;
                            self.lperson = data.lperson;
                            self.phone = data.phone;
                            self.idcode = data.idcode;
                            self.email = data.email;
                            self.address = data.address
                        }

                        if (!hlUrlUtil.GetQueryString('isFromBusinessDetails')) {
                            window.sessionStorage.removeItem('RENT_BUSINESS_CUSTOMER')
                        }

                        self.getChannelNameData()
                    }
                })
            },
            getChannelNameData() {
                var self = this
                hlhttp.get({
                    url: 'configure/dict',
                    data: { module_code: 'ZHSH', config_name: 'ZS_CHANNEL_NAME' },
                    success: data => {
                        self.allchannelNameData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])

                        console.log(self.allchannelNameData);

                        console.log(self.selectedChannelType);
                        self.allchannelNameData.map(item => {
                            if (item.parentDictCode == self.selectedChannelType[0]) {
                                this.channelNameData.push(item)
                            }
                        })
                        console.log(self.channelNameData );
                    }
                })
            },
            getProcessData() {
                var self = this
                hlhttp.get({
                    url: 'configure/dict',
                    data: { module_code: 'ZHSH', config_name: 'ZS_PROCESS_MANAGER' },
                    success: data => {
                        self.processData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
                    }
                })
            },

            handleChannelTypeChange(data) {
                this.channelNameData = []
                this.allchannelNameData.map(item => {
                    if (item.parentDictCode == data[0].dictCode) {
                        this.channelNameData.push(item)
                    }
                })
                this.selectedChannelName = []
                this.selectedChannelTypeVal = data[0]['name'].split()
            },


            handleChannelNameChange(data) {
                this.selectedChannelNameVal = data[0]['code'].split()
            },
						
						resMake (type, val) {
							// text  textarea mobile email phone  time date  dateTime
							let t0 = ['text', 'email', 'area', 'mobile', 'phone', 'time', 'date', 'dateTime', 'select', 'radio', 'checkbox'];						
							let t1 = ['file'];
							if (t0.indexOf(type) > -1) return val;
							if (t1.indexOf(type) > -1) {
								let data = []
								if (val) {
									val.map(item => {
										data.push(item.response ? item.response : item)
									})
								}
								return data
							}
						},
						
						// 新的自定义字段
						newFieldsData () {
							let data = [];
							this.resData.map(item => {
								data.push({
									component_code: item.code,
									component_type: item.type,
									property: this.resMake(item.type, item.value)
								})
							})
							return data;
						},
						
            postCm() {

                var data = {
                    type: this.typeAct,
                    name: this.cmName,
                    industry: this.selectedIndustry.length ? this.selectedIndustry.join() : '#',
                    lperson: this.lperson,
                    phone: this.phone,
                    channel_name_code: this.selectedChannelName.length ? this.selectedChannelName.join() : '#',
                    channel_name_value: this.selectedChannelNameVal.length ? this.selectedChannelNameVal.join() : '#',
                    channel_category_code: this.selectedChannelType.length ? this.selectedChannelType.join() : '#',
                    customer_state: this.selectedCustomerState.length ? this.selectedCustomerState.join() : '#',
                    memo: this.memo,
                    black_state: this.blacklistAct,
                    idcode: this.idcode || '#',
                    email: this.email || '#',
                    short_name: this.jcName,
                    process_type: this.selectedProcess.length ? this.selectedProcess.join() : '#',
                    address: this.address || '#',
                    zipcode: this.zipcode || '#',
                    is_myself: hlUrlUtil.GetQueryString('page') == 'customerMy' ? 'Y' : 'N',
                    custom_config_property: JSON.stringify(this.fieldData),
										page_customize_component_biz_content: JSON.stringify(this.newFieldsData()),
                    biz_info: JSON.stringify(this.infodetail),
					
					loss_reason: this.lsSelectData && this.lsSelectData.length ? this.lsSelectData[0] : '#'
                }
                const businessData = {
                    sj_id: hlUrlUtil.GetQueryString('businessId'),
                    type: this.typeAct,
                    name: this.cmName,
                    industry: this.selectedIndustry.length ? this.selectedIndustry.join() : '#',
                    lperson: this.lperson,
                    phone: this.phone,
                    channel_name: this.selectedChannelName.length ? this.selectedChannelName.join() : '#',
                    channel_name_value: this.selectedChannelNameVal.length ? this.selectedChannelNameVal.join() : '#',
                    channel_type: this.selectedChannelType.length ? this.selectedChannelType.join() : '#',
                    customer_state: this.selectedCustomerState.length ? this.selectedCustomerState.join() : '#',
                    memo: this.memo || '#',
                    black_state: this.blacklistAct,
                    idcode: this.idcode || '#',
                    email: this.email || '#',
                    short_name: this.jcName || '#',
                    process_type: this.selectedProcess.length ? this.selectedProcess.join() : '#',
                    address: this.address || '#',
                    zipcode: this.zipcode || '#',
                    custom_config_property: JSON.stringify(this.fieldData),
										page_customize_component_biz_content: JSON.stringify(this.newFieldsData()),
                    biz_info: JSON.stringify(this.infodetail),
					
					loss_reason: this.lsSelectData && this.lsSelectData.length ? this.lsSelectData[0] : '#'
                }
				
				
								
                var sendAddCustomer = () => {
                    hlhttp.post({
                        url: 'customer',
                        data,
                        success: (res) => {
                            if (!res.customerId) return;
                            hl.toast('创建成功')
                            hlUrlUtil.goTo('customerDetails', { id: res.customerId, ddtab: true, page: 'customerManagement' })
                        }
                    })
                }

                var sendBusinessConvertToCustomer = () => {
                    hlhttp.put({
                        url: 'customer/biz_oppt_to_customer',
                        data: businessData,
                        success: res => {
                            hl.toast('创建成功')
                            hlUrlUtil.goTo('customerDetails', { id: res.customerId, ddtab: true, page: 'customerManagement' })
                        }
                    })
                }

                const isFromBusiness = hlUrlUtil.GetQueryString('isFromBusinessDetails')
                if (isFromBusiness) {
                    sendBusinessConvertToCustomer()
                } else {
                    sendAddCustomer()
                }

            },
            fieldConfig() {
                var that = this;
								return
                hlhttp.get({
                    url: 'configure/customize_column',
                    data: {
                        module: 'ZHSH',
                        config_name: 'ZS_CUSTOMIZE_COLUMNS',
                    },
                    success: (res) => {
                        let arr = [...res.customizeColumns, ...res.systemColumns]
                        for (var i = arr.length - 1; i >= 0; i--) {
                            if (arr[i].isValid == 'false') {
                                arr.splice(i, 1)
                            }
                        }
                        //去除多余数据（未启动，无关联）
                        // if(val){
                        //   arr = hlArrayUtil.removeRepeat([...val,...arr], 'configCode');
                        // }

                        //若有合同详情，则合并,去重（保留合同）
                        let textList = []
                        let noTextList = []
                        arr.map((item, index) => {
                            if (item.fieldType == 'text') {
                                textList.push(item)
                            } else {
                                noTextList.push(item)
                            }
                        })
                        arr = [...noTextList, ...textList]
                            //重新排序，将文本类型放到最后

                        arr.map(item => {
                            if (!item.select) {
                                if (item.fieldType == 'radio' || item.fieldType == 'checkbox' || item.fieldType == 'select') {
                                    item.select = [];
                                    item.selectArr = item.fieldRange.split(',')
                                    item.selectArrCopy = []
                                    item.selectArr.map(item0 => {
                                        item.selectArrCopy.push({
                                            name: item0,
                                            code: item0
                                        })
                                    })
                                } else {
                                    item.select = '';
                                }
                            }
                        })
                        that.fieldData = arr
                    }
                })
            },
            //自定义字段radio选择
            radioSelected(i, code) {
                this.fieldData[i].select = code
            },
            //自定义字段checkbox选择
            checkboxSelected(i, code) {
                if (this.fieldData[i].select.indexOf(code) == -1) {
                    this.fieldData[i].select.push(code)
                    return
                }
                this.fieldData[i].select.splice(this.fieldData[i].select.indexOf(code), 1)
            },
						
						ZS_CUSTOMER_STATUS() {
						    var self = this
						    hlhttp.get({
						        url: 'configure/dict',
						        data: { module_code: 'ZHSH', config_name: 'ZS_CUSTOMER_STATUS' },
						        success: data => {
						            self.customerStateData = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
						        }
						    })
						},
        },
        mounted() {
            // hlSelectUi()
            this.getIndustryData()
            this.getChannelTypeData()
            this.getProcessData()
						this.ZS_CUSTOMER_STATUS()
            this.fieldConfig()
			
			
			this.getLsReason()
        }
    })
}())
